package com.ruoyi.erp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import org.springframework.stereotype.Service;
import com.ruoyi.common.core.mybatisplus.core.ServicePlusImpl;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.erp.domain.bo.InventoryTypeBo;
import com.ruoyi.erp.domain.vo.InventoryTypeVo;
import com.ruoyi.erp.domain.InventoryType;
import com.ruoyi.erp.mapper.InventoryTypeMapper;
import com.ruoyi.erp.service.IInventoryTypeService;

import java.util.List;
import java.util.Collection;

/**
 * 物料类型Service业务层处理
 *
 * @author chenyun
 * @date 2022-03-06
 */
@Service
public class InventoryTypeServiceImpl extends ServicePlusImpl<InventoryTypeMapper, InventoryType, InventoryTypeVo> implements IInventoryTypeService {
    private static final String UNIQUE_KEY = "inv_type_code";
    private static final String LOCK_KEY = "InventoryType:inv_type_code";
    @Override
    public InventoryTypeVo queryById(Long id){
        return getVoById(id);
    }


    @Override
    public List<InventoryTypeVo> queryList(InventoryTypeBo bo) {
        LambdaQueryWrapper<InventoryType> lqw = buildQueryWrapper(bo);
        return listVo(lqw);
    }

    @Override
    public Boolean insertByBo(InventoryTypeBo bo) throws Exception{
        InventoryType add = BeanUtil.toBean(bo, InventoryType.class);
        validEntityBeforeSave(add);
        QueryWrapper wrapper = existQueryWrapper(add);
        boolean flag = insertIdempotency(add,LOCK_KEY,wrapper,getMsg(add));
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    @Override
    public Boolean updateByBo(InventoryTypeBo bo) throws Exception{
        InventoryType update = BeanUtil.toBean(bo, InventoryType.class);
        validEntityBeforeSave(update);
        QueryWrapper wrapper = existQueryWrapper(update);
        boolean flag = updateIdempotency(update,LOCK_KEY,wrapper,getMsg(update));
        return flag;
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(InventoryType entity){
        //TODO 做一些数据校验,如唯一约束
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return removeByIds(ids);
    }

    /**
     * 唯一判断查询条件，暂支持一个键
     * @param entity
     * @return
     */
    private QueryWrapper<InventoryType> existQueryWrapper(InventoryType entity) {
        return new QueryWrapper<InventoryType>().eq(UNIQUE_KEY, entity.getInvTypeCode());
    }

    private String getMsg(InventoryType entity){
            String unique = String.valueOf(entity.getInvTypeCode());
            return "编码["+unique+"]已存在";
    }
}
